<?php
declare(strict_types=1);

namespace lib\service;

use sys\Log;

/**
 * GDS 商品条码查询接口
 */
class Gds {
    public static function query(string $code){
        if(!preg_match('#^\d{13}$#', $code)){
            return json(['success'=>false,'message'=>'条码非法!']);
        }
        // URL: https://bff.gds.org.cn/gds/searching-api/ProductService/ProductListByGTIN?PageSize=30&PageIndex=1&SearchItem='.$code
        Log::write("begin request ....",'DEBUG');
        $result = http_get('https://bff.gds.org.cn/gds/searching-api/ProductService/ProductListByGTIN?PageSize=30&PageIndex=1&SearchItem='.$code, [
            'Accept'=>'application/json, text/plain, */*',
            'Accept-Encoding'=>'gzip, deflate, br',
            'Accept-Language'=>'zh-CN,zh;q=0.9',
            'Cache-Control'=>'no-cache',
            'Connection'=>'keep-alive',
            'DNT'=>'1',
            'Host'=>'bff.gds.org.cn',
            'Origin'=>'https://www.gds.org.cn',
            'Pragma'=>'no-cache',
            'Referer'=>'https://www.gds.org.cn/',
            'Sec-Fetch-Dest'=>'empty',
            'Sec-Fetch-Mode'=>'cors',
            'Sec-Fetch-Site'=>'same-site',
            'User-Agent'=>'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36',
            'currentRole'=>'Mine',
            'sec-ch-ua'=>'"Not.A/Brand";v="8", "Chromium";v="114", "Google Chrome";v="114"',
            'sec-ch-ua-mobile'=>'?0',
            'sec-ch-ua-platform'=>'"Windows"'
        ]);
        Log::write("edn request " . json_encode($result, JSON_UNESCAPED_UNICODE), 'DEBUG');
        if($result['code'] === 200){
            $result = json_decode($result['body'], true);
            echo json_encode($result, JSON_UNESCAPED_UNICODE);
        }
    }
}